#include "CSoundManager.h"
#include "CCore.h"
#include "CException.h"

std::auto_ptr<CSoundManager> CSoundManager::m_instance;

CSoundManager::CSoundManager()
{

}

CSoundManager::~CSoundManager()
{
    Release();
}

bool CSoundManager::Release()
{
    PlayMusic.clear();
    for (int i = (int)Sounds.size() - 1; i >=0; i--){
        delete Sounds[i];
        Sounds[i] = NULL;
    }
    Sounds.clear();
    SDL_QuitSubSystem(SDL_INIT_AUDIO);
    return true;
}

bool CSoundManager::DeleteSound(CFx **p_Sound)
{
    if (p_Sound && *p_Sound){
        for (int i = (int)Sounds.size()-1; i >=0; i--){
            if (Sounds[i] == *p_Sound){
                delete Sounds[i];
                *p_Sound = NULL;
                Sounds.erase(Sounds.begin()+i);
                return true;
            }
        }
    }
    return false;
}

CFx * CSoundManager::LoadSound(const std::string& cp_chFileName,bool bIsFX)
{
    for (int i = (int)Sounds.size()-1; i>=0; i--){
        if (!Sounds[i]->FileName.compare(cp_chFileName)){
            CFx *p_Sound = new CFx();
            p_Sound->bIsFX = bIsFX;
            p_Sound->LoadFromFile(cp_chFileName);
            Sounds.push_back(p_Sound);
            return p_Sound;
        }
    }

    CFx *p_Sound = new CFx();
    if (p_Sound){
        if (p_Sound->LoadFromFile(cp_chFileName))
            Sounds.push_back(p_Sound);
        else{
            delete p_Sound;
            p_Sound = NULL;
        }
        return p_Sound;
    }

    CException("[CSoundManager::LoadSound@80] Error: Return can't be NULL.").Raise();
    return NULL;
}

bool CSoundManager::Initialize()
{
    int iResult1 = SDL_InitSubSystem(SDL_INIT_AUDIO);
    int iResult2 = Mix_OpenAudio(22050,AUDIO_S16,2,4096);

    if ((iResult1 || iResult2) < 0)
        return false;
    return true;
}

void CSoundManager::Update()
{

}
